﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace KhoaLuan.Models
{
    public class ShoppingCart
    {
        public static ShoppingCart Cart
        {
            get
            {
                var cart = HttpContext.Current.Session["Cart"] as ShoppingCart;
                if (cart == null)
                {
                    cart = new ShoppingCart();
                    HttpContext.Current.Session["Cart"] = cart;

                }
                return cart;
            }
        }
        public List<Product> Items = new List<Product>();
        public int Count
        {
            get
            {
                if (Items.Count > 0)
                {
                    return Items.Sum(p => p.Quantity);
                }
                return 0;
            }
        }
        public double Amount
        {
            get
            {
                if (Items.Count > 0)
                {
                    return Items.Sum(p => p.Quantity * p.UnitPrice * (1 - p.Discount));

                }
                return 0;
            }
        }
        public void Add(int Id)
        {
            try
            {
                var p = Items.Single(i => i.Id == Id);
                p.Quantity++;

            }
            catch
            {
                using (var db = new LuanVanEntities())
                {
                    var p = db.Products.Find(Id);
                    p.Quantity = 1;
                    Items.Add(p);
                }
            }
        }
        public void Remove(int Id)
        {
            var p = Items.Single(i => i.Id == Id);
            Items.Remove(p);

        }
        public void Clear()
        {
            Items.Clear();
        }
        public void Update(int Id, int NewQuantity)
        {
            var p = Items.Single(i => i.Id == Id);
            p.Quantity = NewQuantity;
        }
    }
}